<?php

namespace Frieza\Modules\Browseuser\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\BrowseUserIndex;


class BrowseuserController extends Controller
{

    const PAGE_SIZE = 20;


    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', 20);
        if(isset($params['theme'])) {
            $request->merge(['theme'=>$params['theme']]);
        }
        if(isset($params['obj_id'])) {
            $request->merge(['obj_id'=>$params['obj_id']]);
        }

        return $content
            ->header('主页非生产用户配置页(<span style="color:red;">当配置了多条数据时，仅最新的配置会生效</span>)')
            ->breadcrumb(
                [
                    'text' => '主页非生产用户配置页',
                    'url'  => '/browseuser/index'
                ]
            )
            ->body(self::listAction($params));
    }


    private function listAction($params = [])
    {

        $data = BrowseUserIndex::getIndexs();
        if($data && is_array($data)) {
            foreach($data as &$indexInfo) {
                $indexLink = LinkFormat::generateLink($indexInfo['link_type'], $indexInfo['link_params']);
                $link = ($indexLink && isset($indexLink['app_template'])) ? $indexLink['app_template'] : '';
                $indexInfo['link'] = $link;
            }
        }


        $gridModel = new pGridDataModel($data, count($data), []);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();
            $grid->paginate(20);
            $grid->column('id')->width(50);
            $grid->column('info', '描述文案');
            $grid->column('pic_id', '引导插画')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $this->pic_id, ImgUrl::IMAGE_SIZE_OP_ORI)."' width='200' />";
            });
            $grid->column('extra_info', '弹窗说明文案');
            $grid->column('btn_info', '按钮文案');
            $grid->column('link', '链接地址')->linkSelect(false, null, false);
            $grid->column('addtime', '时间')->display(function() {
                return "创建时间：".$this->addtime."<br/>最后修改时间".$this->edittime;
            });
            $grid->column('admin_id', '最后操作人')->display(function() {
                return Admin::user()->find($this->admin_id)->name;
            });
        });

        return $listGrid;
    }


    //新建/编辑页面
    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑配置页';
        } else {
            $title = '创建配置页';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('主页非生产用户配置页')
            ->breadcrumb(
                [
                    'text' => '配置列表',
                    'url'  => '/browseuser/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {
        if ($id > 0) {
            $data = BrowseUserIndex::getIndexInfo($id);
            $data['link'] = [
                "link_type" => $data['link_type'],
                "link_params" => $data['link_params']
            ];
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->text('info', '描述文案')->required('必填');
        $form->imgUpload('pic_id', '引导插画', false, ['imgType' => ImgUrl::APPTYPE_OP, 'imgSize' => ImgUrl::IMAGE_SIZE_OP_ORI]);
        $form->text('extra_info', '弹窗说明文案')->required('必填');
        $form->text('btn_info', '按钮文案')->required('必填');
        $form->linkSelect('link', '按钮链接');

        $form->action('/admin/browseuser/index/save');

        return $form;
    }

    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $data = [
            'info' => $params['info'],
            'pic_id' => $params['pic_id'],
            'extra_info' => $params['extra_info'],
            'btn_info' => $params['btn_info'],
            'link_type' => $params['link_type'],
            'link_params' => json_encode($params['link_params'], JSON_UNESCAPED_UNICODE),
            'index_status' => BrowseUserIndex::STATUS_NORMAL,
            'admin_id' => Admin::user()->id,
        ];

        if(isset($params['id']) && $params['id']) {
            //编辑
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = BrowseUserIndex::editData($params['id'], $data);

        } else {
            //创建
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = BrowseUserIndex::addData($data);
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/browseuser/index')->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delIndex($id)
    {

        $rs = BrowseUserIndex::editData($id, [
            "edittime" => date('Y-m-d H:i:s', time()),
            "index_status" => BrowseUserIndex::STATUS_DELETE,
            "admin_id" => Admin::user()->id
        ]);

        if($rs) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }

    }

}
